package com.wits.platform.web.controller;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;

import javax.servlet.http.HttpServletRequest;

import org.apache.shiro.SecurityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource;
import org.springframework.context.support.MessageSourceAccessor;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.servlet.i18n.SessionLocaleResolver;

import com.wits.platform.common.exception.I18nServiceException;
import com.wits.platform.service.account.ShiroUser;
import com.wits.platform.web.mvc.AjaxResult;
import com.wits.platform.web.mvc.support.editor.DateEditor;
public class BaseController{
	
	protected final Logger logger = LoggerFactory.getLogger(getClass());
    
    
	public static final String MESSAGES_KEY = "messages";

	public static final String ERRORS_KEY="errors";
	
	
	private MessageSourceAccessor messages;

	
	
	public HttpServletRequest getRequest(){
		return ((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getRequest();
	}
	
	
    @Autowired
    public void setMessages(MessageSource messageSource) {
        messages = new MessageSourceAccessor(messageSource);
    }
    
	@SuppressWarnings("unchecked")
	public void addError(HttpServletRequest request, String error) {
		List<String> errorList = (List<String>) request.getSession().getAttribute(ERRORS_KEY);
		if (errorList == null) {
			errorList = new ArrayList<String>();
		}
		errorList.add(error);
		request.getSession().setAttribute(ERRORS_KEY, errorList);
	}

	@SuppressWarnings("unchecked")
	public void addMessage(HttpServletRequest request, String msg) {
		List<String> messageList = (List<String>) request.getSession().getAttribute(MESSAGES_KEY);
		if (messageList == null) {
			messageList = new ArrayList<String>();
		}
		messageList.add(msg);
		request.getSession().setAttribute(MESSAGES_KEY, messageList);
	}

	
	public void saveMessage(HttpServletRequest request,String error) {
		request.setAttribute(ERRORS_KEY, error);
	}
	
	
	
	public String getText(String msgKey) {
		return getText(msgKey,getLocale());
	}
	
	public String getText(String msgKey, Locale locale) {
		return messages.getMessage(msgKey, locale);
	}

	public String getText(String msgKey, Object... args) {
		return getText(msgKey,getLocale(),args);
	}
	
	public String getText(String msgKey,Locale locale,Object... args) {
		return messages.getMessage(msgKey, args,locale);
	}

	@InitBinder
	protected void initBinder(HttpServletRequest request,WebDataBinder binder) {
		String formater=getText("date.format");
		binder.registerCustomEditor(Date.class, new DateEditor(formater));
	}
	
	
	
	public void setLocale(String localeStr){
		Locale locale=null;
		HttpServletRequest request=getRequest();
		if(localeStr!=null && localeStr.indexOf("_")>0){
			String[] arr=localeStr.split("_");
			locale=new Locale(arr[0],arr[1]);
		}else{
			locale=request.getLocale();
		}
		request.getSession().setAttribute(SessionLocaleResolver.LOCALE_SESSION_ATTRIBUTE_NAME,locale);
	}
	
	public Locale getLocale(){
		HttpServletRequest request=getRequest();
		if(request!=null){
			return (Locale)request.getSession().getAttribute(SessionLocaleResolver.LOCALE_SESSION_ATTRIBUTE_NAME);
		}
		return null;
	}
	
	public String getLocaleString(){
		Locale locale=getLocale();
		if(locale!=null){
			return locale.toString();
		}
		return null;
	}
	
	
	
	/**
	 * 取出Shiro中的当前用户.
	 */
	protected ShiroUser getCurrentUser() {
		return (ShiroUser) SecurityUtils.getSubject().getPrincipal();
	}
	
	protected String getCurrentUserId() {
		ShiroUser user=(ShiroUser) SecurityUtils.getSubject().getPrincipal();
		return user.getId();
	}
	
	
	
	
	protected AjaxResult ajaxDoneError(){
		return AjaxResult.error();
	}
	
	protected AjaxResult ajaxDoneError(String message){
		return AjaxResult.error(message);
	}
	
	protected AjaxResult ajaxDoneError(String title,Exception e){
		String message=e!=null?e.getMessage():title;
		if(e instanceof I18nServiceException){
			I18nServiceException i18nE=(I18nServiceException)e;
			if(i18nE.getErrorKey()!=null){
				message=this.getText(i18nE.getErrorKey());
			}
		}
		return AjaxResult.error(title,message);
	}
	
	protected AjaxResult ajaxDoneSuccess(){
		return AjaxResult.success();
	}
	
	protected AjaxResult ajaxDoneSuccess(String message){
		return AjaxResult.success(message);
	}
	
	protected AjaxResult ajaxDoneSuccess(String title,String message){
		return AjaxResult.success(title,message);
	}
	
	protected AjaxResult ajaxDoneSuccess(Object data){
		return AjaxResult.success(data);
	}
	
	
    @Override
	public String toString() {
		return getClass().getSimpleName();
	}
	
}
